package com.fau.template.shiro;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import com.fau.template.entity.NmAdmin;
import com.fau.template.entity.NmResource;
import com.fau.template.entity.NmRole;
import com.fau.template.service.IUserManagerService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;

/**
 * @desc 自定义权限认证
 * @author liy
 * @datetime 2015年5月15日,下午10:27:54
 */
@Service
@Transactional
public class MyRealm extends AuthorizingRealm {

    @Resource(name = "userManagerService")
    private IUserManagerService userManagerService;

    /**
     * @desc 权限认证
     * @return AuthorizationInfo
     * @author liy
     * @datetime 2015年5月15日,下午11:09:17
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取登录的用户名
        String username = (String) getAvailablePrincipal(principalCollection);

        NmAdmin admin = userManagerService.findUserByName(username);
        if(null != admin){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 登录的用户有多少个角色
            Set<String> roleNames = new HashSet<String>();

            Set<NmRole> roles = admin.getRoleSet();
            for (NmRole nmRole : roles) {
                roleNames.add(nmRole.getName());

                // 角色有多少个权限
                Set<NmResource> resources = nmRole.getResourceSet();
                Set<String> resourceNames = new HashSet<String>();
                for (NmResource nmResource : resources) {
                    resourceNames.add(nmResource.getUrl());
                }
                info.addStringPermissions(resourceNames);
            }

            info.setRoles(roleNames);

            return info;
        } else {
            return null;
        }

    }

    /**
     * @desc 登录认证
     * @return AuthenticationInfo
     * @throws AuthenticationException
     * @author liy
     * @datetime 2015年5月15日,下午11:09:46
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        NmAdmin admin = userManagerService.findUserByName(token.getUsername());
        if(null != admin) {
            return new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), admin.getName());
        } else {
            return null;
        }
    }
}